package com.taoyige.api;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.taoyige.AppConfig;
import com.taoyige.AppContext;
import com.taoyige.AppException;
import com.taoyige.bean.Address;
import com.taoyige.bean.AddressList;
import com.taoyige.bean.Goods;
import com.taoyige.bean.Order;
import com.taoyige.bean.OrderList;
import com.taoyige.bean.Result;
import com.taoyige.bean.URLs;
import com.taoyige.bean.Update;
import com.taoyige.bean.User;
import com.taoyige.bean.WXAccessInfo;
import com.taoyige.bean.WXUserInfo;
import com.taoyige.bean.WelcomeImage;
import com.taoyige.common.FileUtils;
import com.taoyige.common.ImageUtils;
import com.taoyige.common.StringUtils;

/**
 * API客户端接口：用于访问网络数据
 * 
 * @author peter
 * @version 1.0
 * @date 2014-11-12
 */
public class ApiClient {

	public static final String UTF_8 = "UTF-8";
	public static final String DESC = "descend";
	public static final String ASC = "ascend";

	private final static int TIMEOUT_CONNECTION = 20000;
	private final static int TIMEOUT_SOCKET = 20000;
	private final static int RETRY_TIME = 3;

	private static String appCookie;
	private static String appUserAgent;

	public static void cleanCookie() {
		appCookie = "";
	}

	private static String getCookie(AppContext appContext) {
		if (appCookie == null || appCookie == "") {
			appCookie = appContext.getProperty("cookie");
		}
		return appCookie;
	}
	
	public static JSONObject getLocation(AppContext appContext,InputStream inputStream) throws AppException {
		try{
		    byte [] buffer = new byte[inputStream.available()];  
		    while (inputStream.read(buffer) != -1);  
		    String json = new String(buffer);  
		    JSONObject obj = new JSONObject(json);
			return obj;
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 首页商品信息
	 * 
	 * @param appContext
	 * @return
	 * @throws AppException
	 */
	public static Goods goodsIndex(AppContext appContext) throws AppException {
		try {
			return Goods.parse(http_get(appContext, URLs.GOODS_INDEX));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}

	/**
	 * 首页即将开始信息
	 * 
	 * @param appContext
	 * @return
	 * @throws AppException
	 */
	public static Goods goodsCommingSoon(AppContext appContext)
			throws AppException {
		try {
			return  Goods.parse(http_get(appContext, URLs.GOODS_COMMING_SOON));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}

	/**
	 * 商品详情信息
	 * 
	 * @param appContext
	 * @return
	 * @throws AppException
	 */
	public static Goods goodsDetail(AppContext appContext, final Long goodsId)
			throws AppException {

		String newUrl = _makeURL(URLs.GOODS_DETAIL,
				new HashMap<String, Object>() {
					{
						put("goodsId", goodsId);
					}
				});
		try {
			return Goods.parse(http_get(appContext, newUrl));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}

	/**
	 * 查询用户信息
	 * 
	 * @param appContext
	 * @return
	 * @throws AppException
	 */
	public static User userInfo(AppContext appContext, final String uid)
			throws AppException {
		String newUrl = _makeURL(URLs.USER_INFO, new HashMap<String, Object>() {
			{
				put("uid", uid);
			}
		});
		try {
			return User.parse(http_get(appContext, newUrl));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 保存用户信息
	 * 
	 * @param appContext
	 * @param addr
	 * @return
	 * @throws AppException
	 */
	public static User userAdd(AppContext appContext, User user)
			throws AppException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(User.USER_NAME, user.getUserName());
		params.put(User.USER_PID,  user.getPid());
		params.put(User.USER_P_USER_ID,  user.getpUserID());
		params.put(User.USER_P_USER_NAME,  user.getpUserName());
		params.put(User.USER_THUMB_URL,  user.getThumbUrl());

		try {
			return User.parse(_post(appContext, URLs.USER_ADD, params));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}
	
	
	/**
	 * 用户默认地址信息
	 * 
	 * @param appContext
	 * @return
	 * @throws AppException
	 */
	public static Address addrDefault(AppContext appContext, final String uid)
			throws AppException {
		String newUrl = _makeURL(URLs.ADDR_DEFAULT, new HashMap<String, Object>() {
			{
				put("uid", uid);
			}
		});
		try {
			return Address.parse(http_get(appContext, newUrl));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 用户地址列表信息
	 * 
	 * @param appContext
	 * @return
	 * @throws AppException
	 */
	public static AddressList addList(AppContext appContext, final String uid)
			throws AppException {
		String newUrl = _makeURL(URLs.ADDR_LIST, new HashMap<String, Object>() {
			{
				put("uid", uid);
			}
		});
		try {
			return AddressList.parse(http_get(appContext, newUrl));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 删除地址
	 * 
	 * @param appContext
	 * @param addr
	 * @return
	 * @throws AppException
	 */
	public static Address delAddress(AppContext appContext, String uid,String id)
			throws AppException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id",id);
		params.put("uid", uid);
		try {
			Address result = Address.parse(_post(appContext, URLs.ADDR_DEL, params));
			return result;
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 用户默认地址
	 * 
	 * @param appContext
	 * @param addr
	 * @return
	 * @throws AppException
	 */
	public static Address setAddressDefault(AppContext appContext, String id,String uid)
			throws AppException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id",id);
		params.put("uid",uid);
		try {
			Address result = Address.parse(_post(appContext, URLs.ADDR_SET_DEFAULT, params));
			return result;
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 保存用户地址
	 * 
	 * @param appContext
	 * @param addr
	 * @return
	 * @throws AppException
	 */
	public static Address addrAdd(AppContext appContext, Address addr)
			throws AppException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("uid", addr.getUserID());
		params.put(Address.ADDR_NAME, addr.getName());
		params.put(Address.ADDR_PROVINCE, addr.getProvince());
		params.put(Address.ADDR_CITY, addr.getCity());
		params.put(Address.ADDR_COUNTY, addr.getCounty());
		params.put(Address.ADDR_POSTCODE, addr.getPostcode());
		params.put(Address.ADDR_DETAILS, addr.getDetails());
		params.put(Address.ADDR_MOBILE_PHONE, addr.getMobilephone());

		try {
			return Address.parse(_post(appContext, URLs.ADDR_ADD, params));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 更新用户地址
	 * 
	 * @param appContext
	 * @param addr
	 * @return
	 * @throws AppException
	 */
	public static Address addrUpdate(AppContext appContext, Address addr)
			throws AppException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(Address.ADDR_ID, addr.getId());
		params.put(Address.ADDR_NAME, addr.getName());
		params.put(Address.ADDR_PROVINCE, addr.getProvince());
		params.put(Address.ADDR_CITY, addr.getCity());
		params.put(Address.ADDR_COUNTY, addr.getCounty());
		params.put(Address.ADDR_POSTCODE, addr.getPostcode());
		params.put(Address.ADDR_DETAILS, addr.getDetails());
		params.put(Address.ADDR_MOBILE_PHONE, addr.getMobilephone());

		try {
			return Address.parse(_post(appContext, URLs.ADDR_UPDATE, params));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}

	
	/**
	 * 订单详情信息
	 * 
	 * @param appContext
	 * @return
	 * @throws AppException
	 */
	public static Order orderDetail(AppContext appContext,final String id, final String uid) throws AppException {
		String newUrl =  _makeURL(URLs.ORDER_DETAIL, new HashMap<String, Object>() {
			{
				put("id", id);
				put("uid", uid);
			}
		});

		try {
			return Order.parse(http_get(appContext, newUrl));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 用户已付款订单列表信息
	 * 
	 * @param appContext
	 * @return
	 * @throws AppException
	 */
	public static OrderList orderPaidList(AppContext appContext, final String uid,final Integer start,
			final Integer count) throws AppException {
		String newUrl =  _makeURL(URLs.ORDER_PAID, new HashMap<String, Object>() {
			{
				put("start", start);
				put("count", count);
				put("uid", uid);
			}
		});

		try {
			return OrderList.parse(http_get(appContext, newUrl));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}

	/**
	 * 用户未付款订单列表信息
	 * 
	 * @param appContext
	 * @return
	 * @throws AppException
	 */
	public static OrderList orderUnPaidList(AppContext appContext, final String uid,final Integer start,
			final Integer count) throws AppException {
		String newUrl =  _makeURL(URLs.ORDER_UNPAID, new HashMap<String, Object>() {
			{
				put("start", start);
				put("count", count);
				put("uid", uid);
			}
		});
		try {
			return OrderList.parse(http_get(appContext, newUrl));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 用户已完成订单列表信息
	 * 
	 * @param appContext
	 * @return
	 * @throws AppException
	 */
	public static OrderList orderCompleteList(AppContext appContext, final String uid,final Integer start,
			final Integer count) throws AppException {
		String newUrl =  _makeURL(URLs.ORDER_COMPLETE, new HashMap<String, Object>() {
			{
				put("start", start);
				put("count", count);
				put("uid", uid);
			}
		});

		try {
			return OrderList.parse(http_get(appContext, newUrl));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 更新订单为确认收货信息
	 * 
	 * @param appContext
	 * @param orderId
	 * @param uid
	 * @return
	 * @throws AppException
	 */
	public static Order orderRecepit(AppContext appContext, String orderId,String uid)
			throws AppException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(Order.ORDER_ID, orderId);
		params.put("uid", uid);
		try {
			return Order
					.parse(_post(appContext, URLs.ORDER_RECEPIT, params));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 更新订单为已付款信息
	 * 
	 * @param appContext
	 * @param orderId
	 * @return
	 * @throws AppException
	 */
	public static Order orderPaid(AppContext appContext, String orderId)
			throws AppException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(Order.ORDER_ID, orderId);
		
		try {
			return Order
					.parse(_post(appContext, URLs.ORDER_PAY, params));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}

	/**
	 * 取消订单
	 * 
	 * @param appContext
	 * @param orderId
	 * @return
	 * @throws AppException
	 */
	public static Order orderCancel(AppContext appContext, String orderId,String uid)
			throws AppException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(Order.ORDER_ID, orderId);
		params.put("uid", uid);
		try {
			return Order
					.parse(_post(appContext, URLs.ORDER_CLOSE, params));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 保存订单信息
	 * 
	 * @param appContext
	 * @param addr
	 * @return
	 * @throws AppException
	 */
	public static Order orderAdd(AppContext appContext, Order order)
			throws AppException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(Order.ORDER_USER_ID, order.getUserID());
		params.put(Order.ORDER_GOODS_ID, order.getProductID());
		params.put(Order.ORDER_COUNT, 1);
		params.put(Order.ORDER_AMOUNT, order.getAmount());
		params.put(Order.ORDER_TOTAL_PRICE, order.getTotalPrice());
		params.put(Order.ORDER_ORIGIN_PRICE, order.getOriPrice());
		//params.put(Order.ORDER_ADDR_INFO, order.getAddressInfo());
		
		params.put("addressInfo", "{\"name\":\""+order.getAddressInfo().getName()+"\",\"mobilephone\":\""+order.getAddressInfo().getMobilephone()+"\",\"details\":\""+
				order.getAddressInfo().getProvinceText()+order.getAddressInfo().getCityText()+order.getAddressInfo().getCountyText()+order.getAddressInfo().getDetails()+"\"}");
		
		
//		params.put(Order.ORDER_EXPRESS_COMPANY, order.getExpressCompany());
//		params.put(Order.ORDER_EXPRESS_NO, order.getExpressNumber());
//		params.put(Order.ORDER_CUSTOM_EXPRESS_INFO,
//				order.getCustomExpressInfo());
//		params.put(Order.ORDER_FREIGHT, order.getFreight());
//		params.put(Order.ORDER_PAYMENT_NOTICE, order.getPaymentNotice());
//		params.put(Order.ORDER_PAYMENT_PLATFORM, order.getPaymentPlatform());
//		params.put(Order.ORDER_OPERATION, order.getOperation());
//		params.put(Order.ORDER_STATUS, order.getStatus());
//		params.put(Order.ORDER_TIMESTAMP, order.getTimestamp());
//		params.put(Order.ORDER_TIMER, order.getTimer());
		
		try {
			return Order
					.parse(_post(appContext, URLs.ORDER_ADD, params));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}

	
	/**
	 * 微信授权登录
	 * 
	 * @param appContext
	 * @return
	 * @throws AppException
	 */
	public static User wechatLogin(AppContext appContext,final String code) throws AppException {
		User user=null;
		String oauth_url="https://api.weixin.qq.com/sns/oauth2/access_token";
		String userinfo_url="https://api.weixin.qq.com/sns/userinfo";
		String new_auth_url =  _makeURL(oauth_url, new HashMap<String, Object>() {
			{
				put("appid", AppConfig.APP_KEY_WECHAT);
				put("secret", AppConfig.APP_SECRET_WECHAT);
				put("code", code);
				put("grant_type","authorization_code");
			}
		});
		try {
			WXAccessInfo accessInfo=WXAccessInfo.parse(http_get(appContext, new_auth_url));
			if(accessInfo!=null){
				final String openid=accessInfo.getOpenid();
				final String access_token=accessInfo.getAccess_token();
				String new_userinfo_url =  _makeURL(userinfo_url, new HashMap<String, Object>() {
					{
						put("openid", openid);
						put("access_token", access_token);
					}
				});
				WXUserInfo userInfo=WXUserInfo.parse(http_get(appContext, new_userinfo_url));
				user=new User();
				user.setUserName(userInfo.getNickname());
				user.setId(AppConfig.LOGIN_OAUTH_WECHAT+"-"+userInfo.getOpenid());
				user.setPid(AppConfig.LOGIN_OAUTH_WECHAT);
				user.setpUserID(userInfo.getOpenid());
				user.setpUserName(userInfo.getNickname());
				user.setThumbUrl(userInfo.getHeadimgurl());
			}
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
		return user;
	}
	
	
	private static String getUserAgent(AppContext appContext) {
		if (appUserAgent == null || appUserAgent == "") {
			StringBuilder ua = new StringBuilder("TAOYIGE.COM");
			ua.append('/' + appContext.getPackageInfo().versionName + '_'
					+ appContext.getPackageInfo().versionCode);// App版本
			ua.append("/Android");// 手机系统平台
			ua.append("/" + android.os.Build.VERSION.RELEASE);// 手机系统版本
			ua.append("/" + android.os.Build.MODEL); // 手机型号
			ua.append("/" + appContext.getAppId());// 客户端唯一标识
			appUserAgent = ua.toString();
		}
		return appUserAgent;
	}

	private static HttpClient getHttpClient() {
		HttpClient httpClient = new HttpClient();
		// 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
		httpClient.getParams().setCookiePolicy(
				CookiePolicy.BROWSER_COMPATIBILITY);
		// 设置 默认的超时重试处理策略
		httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler());
		// 设置 连接超时时间
		httpClient.getHttpConnectionManager().getParams()
				.setConnectionTimeout(TIMEOUT_CONNECTION);
		// 设置 读数据超时时间
		httpClient.getHttpConnectionManager().getParams()
				.setSoTimeout(TIMEOUT_SOCKET);
		// 设置 字符集
		httpClient.getParams().setContentCharset(UTF_8);
		return httpClient;
	}

	private static GetMethod getHttpGet(String url, String cookie,
			String userAgent) {
		GetMethod httpGet = new GetMethod(url);
		// 设置 请求超时时间
		httpGet.getParams().setSoTimeout(TIMEOUT_SOCKET);
		httpGet.setRequestHeader("Host", URLs.HOST);
		httpGet.setRequestHeader("Connection", "Keep-Alive");
		httpGet.setRequestHeader("Cookie", cookie);
		httpGet.setRequestHeader("User-Agent", userAgent);
		return httpGet;
	}

	private static PostMethod getHttpPost(String url, String cookie,
			String userAgent) {
		PostMethod httpPost = new PostMethod(url);
		// 设置 请求超时时间
		httpPost.getParams().setSoTimeout(TIMEOUT_SOCKET);
		httpPost.setRequestHeader("Host", URLs.HOST);
		httpPost.setRequestHeader("Connection", "Keep-Alive");
		httpPost.setRequestHeader("Cookie", cookie);
		httpPost.setRequestHeader("User-Agent", userAgent);
		//httpPost.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8"); 
		return httpPost;
	}

	/**
	 * get请求URL
	 * 
	 * @param url
	 * @throws AppException
	 */
	private static InputStream http_get(AppContext appContext, String url)
			throws AppException {
		String cookie = getCookie(appContext);
		String userAgent = getUserAgent(appContext);

		HttpClient httpClient = null;
		GetMethod httpGet = null;

		String responseBody = "";
		int time = 0;
		do {
			try {
				httpClient = getHttpClient();
				httpGet = getHttpGet(url, cookie, userAgent);
				int statusCode = httpClient.executeMethod(httpGet);
				if (statusCode != HttpStatus.SC_OK) {
					throw AppException.http(statusCode);
				}
				responseBody = httpGet.getResponseBodyAsString();
				break;
			} catch (HttpException e) {
				time++;
				if (time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
					}
					continue;
				}
				// 发生致命的异常，可能是协议不对或者返回的内容有问题
				e.printStackTrace();
				throw AppException.http(e);
			} catch (IOException e) {
				time++;
				if (time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
					}
					continue;
				}
				// 发生网络异常
				e.printStackTrace();
				throw AppException.network(e);
			} finally {
				// 释放连接
				httpGet.releaseConnection();
				httpClient = null;
			}
		} while (time < RETRY_TIME);

		// responseBody = responseBody.replaceAll("\\p{Cntrl}", "\r\n");
		return new ByteArrayInputStream(responseBody.getBytes());
	}

	/**
	 * 公用post方法
	 * 
	 * @param url
	 * @param params
	 * @param files
	 * @throws AppException
	 */
	private static InputStream _post(AppContext appContext, String url,Map<String, Object> params)
			throws AppException {
		String cookie = getCookie(appContext);
		String userAgent = getUserAgent(appContext);

		HttpClient httpClient = null;
		PostMethod httpPost = null;

		// post表单参数处理
		int length = params == null ? 0 : params.size();
		NameValuePair[] np=new NameValuePair[length];
		int i = 0;
		if (params != null)
			for (String name : params.keySet()) {
				np[i++] = new NameValuePair(name, String.valueOf(params.get(name)));
			}
				
		String responseBody = "";
		int time = 0;
		do {
			try {
				httpClient = getHttpClient();
				httpPost = getHttpPost(url, cookie, userAgent);
//				httpPost.setRequestEntity(new MultipartRequestEntity(parts,httpPost.getParams()));
				httpPost.setRequestBody(np);
				int statusCode = httpClient.executeMethod(httpPost);
				if (statusCode != HttpStatus.SC_OK) {
					throw AppException.http(statusCode);
				} else if (statusCode == HttpStatus.SC_OK) {
					Cookie[] cookies = httpClient.getState().getCookies();
					String tmpcookies = "";
					for (Cookie ck : cookies) {
						tmpcookies += ck.toString() + ";";
					}
					// 保存cookie
					if (appContext != null && tmpcookies != "") {
						appContext.setProperty("cookie", tmpcookies);
						appCookie = tmpcookies;
					}
				}
				responseBody = httpPost.getResponseBodyAsString();
				break;
			} catch (HttpException e) {
				time++;
				if (time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
					}
					continue;
				}
				// 发生致命的异常，可能是协议不对或者返回的内容有问题
				e.printStackTrace();
				throw AppException.http(e);
			} catch (IOException e) {
				time++;
				if (time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
					}
					continue;
				}
				// 发生网络异常
				e.printStackTrace();
				throw AppException.network(e);
			} finally {
				// 释放连接
				if(httpPost!=null){
					httpPost.releaseConnection();
					httpClient = null;
				}
			}
		} while (time < RETRY_TIME);

		responseBody = responseBody.replaceAll("\\p{Cntrl}", "");
		/*
		if (responseBody.contains("result")
				&& responseBody.contains("errorCode")
				&& appContext.containsProperty("user.uid")) {
			try {
				Result res = Result.parse(new ByteArrayInputStream(responseBody
						.getBytes()));
				if (res.getErrorCode() == 0) {
					appContext.logout();
					// appContext.getUnLoginHandler().sendEmptyMessage(1);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}*/
		return new ByteArrayInputStream(responseBody.getBytes());
	}


	/**
	 * 获取网络图片
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap getNetBitmap(String url) throws AppException {
		HttpClient httpClient = null;
		GetMethod httpGet = null;
		Bitmap bitmap = null;
		int time = 0;
		do {
			try {
				httpClient = getHttpClient();
				httpGet = getHttpGet(url, null, null);
				int statusCode = httpClient.executeMethod(httpGet);
				if (statusCode != HttpStatus.SC_OK) {
					throw AppException.http(statusCode);
				}
				InputStream inStream = httpGet.getResponseBodyAsStream();
				bitmap = BitmapFactory.decodeStream(inStream);
				inStream.close();
				break;
			} catch (HttpException e) {
				time++;
				if (time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
					}
					continue;
				}
				// 发生致命的异常，可能是协议不对或者返回的内容有问题
				e.printStackTrace();
				throw AppException.http(e);
			} catch (IOException e) {
				time++;
				if (time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
					}
					continue;
				}
				// 发生网络异常
				e.printStackTrace();
				throw AppException.network(e);
			} finally {
				// 释放连接
				if(httpGet!=null){
					httpGet.releaseConnection();
					httpClient = null;
				}
			}
		} while (time < RETRY_TIME);
		return bitmap;
	}

	/**
	 * 检查版本更新
	 * 
	 * @param url
	 * @return
	 */
	public static Update checkVersion(AppContext appContext)
			throws AppException {
		try {
			return Update.parse(http_get(appContext, URLs.UPDATE_APP_VERSION));
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}

	/**
	 * 检查是否有可下载的欢迎界面图片
	 * 
	 * @param appContext
	 * @return
	 * @throws AppException
	 */
	public static void checkBackGround(AppContext appContext)
			throws AppException {
		try {
			WelcomeImage update = WelcomeImage.parse(http_get(appContext,
					URLs.UPDATE_WELCOME_VERSION));
			String filePath = FileUtils.getAppCache(appContext, "welcomeback");
			// 如果没有图片的链接地址则返回
			if (StringUtils.isEmpty(update.getImglist().get(0).getCoverImgUrl())) {
				return;
			}
			if (update.isUpdate()) {
				String url = update.getImglist().get(0).getCoverImgUrl();
				String fileName = update.getStartDate().replace("-", "") + "-"
						+ update.getEndDate().replace("-", "");
				List<File> files = FileUtils.listPathFiles(filePath);
				if (!files.isEmpty()) {
					if (files.get(0).getName().equalsIgnoreCase(fileName)) {
						return;
					}
				}
				Bitmap photo = getNetBitmap(url);
				ImageUtils.saveImageToSD(appContext, filePath + fileName
						+ ".png", photo, 100);
			} else {
				FileUtils.clearFileWithPath(filePath);
			}
		} catch (Exception e) {
			if (e instanceof AppException)
				throw (AppException) e;
			throw AppException.network(e);
		}
	}

	private static String _makeURL(String p_url, Map<String, Object> params) {
		StringBuilder url = new StringBuilder(p_url);
		if (url.indexOf("?") < 0)
			url.append('?');

		for (String name : params.keySet()) {
			url.append('&');
			url.append(name);
			url.append('=');
			url.append(String.valueOf(params.get(name)));
			// 不做URLEncoder处理
			// url.append(URLEncoder.encode(String.valueOf(params.get(name)),
			// UTF_8));
		}

		return url.toString().replace("?&", "?");
	}

}
